package com.web.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.web.dao.BaseDao;


public class BaseDaoImpl<T> implements BaseDao<T>{

	@Autowired
	protected MongoTemplate mongoTemplate;
	


	@Override
	public T findById(String id) {
		return this.mongoTemplate.findById(id, getEntityClass());
	}

	@Override
	public List<T> findAll() {
		 return this.mongoTemplate.findAll(getEntityClass());  
	}

	@Override
	public void remove(T t) {
		this.mongoTemplate.remove(t);  	
	}

	@Override
	public void add(T t) {
		 this.mongoTemplate.insert(t);  	
	}

	@Override
	public void saveOrUpdate(T t) {
		this.mongoTemplate.save(t);  		
	}
	
    /** 
     * 批量插入 
     * @param entityClass 对象类 
     * @param collection  要插入的对象集合 
     */  
    public void addCollection(Collection<T> collection){  
        this.mongoTemplate.insert(collection, getEntityClass());  
    }  
    
    
    @SuppressWarnings("unchecked")
	protected Class<T> getEntityClass() {
	    return ((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
	}
}
